package com.lbc.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.lbc.common.constants.AliPayConstants;
import com.lbc.common.resp.ResponseResult;
import com.lbc.service.DonateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author xyl
 * @date 2021-03-19 19:10
 */
@Api(tags = "捐赠")
@RequestMapping("/donate")
@RestController
public class DonateController {

    @Autowired
    private DonateService donateService;

    @ApiOperation("项目捐赠")
    @PostMapping("/project")
    public Object projectToPay(@RequestParam("projectId")Integer projectId,@RequestParam("money") Float money) {
        return donateService.toDonate(projectId,money,"project");
    }
    @ApiOperation("儿童捐赠")
    @PostMapping("/kid")
    public Object kidToPay(@RequestParam("kidId") Integer kidId,@RequestParam("money") Float money) {
        return donateService.toDonate(kidId,money,"kid");
    }

    @ApiIgnore
    @GetMapping("/notify")
    public ModelAndView notify(HttpServletRequest request) throws AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String, String> maps = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name =  iter.next();
            String[] values =  requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"),"utf-8");
            maps.put(name, valueStr);
        }
        int count = donateService.notifyDonate(maps.get("out_trade_no"));
        boolean signVerified = AlipaySignature.rsaCheckV1(maps, AliPayConstants.alipay_public_key, "UTF-8", "RSA2");
        if (!signVerified) {
            return null;
        }
        return new ModelAndView(AliPayConstants.ALI_RETURN_URL);
    }


    @ApiOperation("捐赠统计")
    @GetMapping("/statistics")
    public ResponseResult getDonateStatistics(){
        return ResponseResult.success(donateService.getDonateStatistics());
    }
    @ApiOperation("个人捐赠记录")
    @GetMapping("/record")
    public ResponseResult getRecord(){
        return ResponseResult.success(donateService.getDonateRecord());
    }
}
